<template>
  <el-card style="width: 450px;margin: 0 auto;padding: 20px 10px 0 0;">
    <h1>登录</h1>
    <el-form label-width="60px">
      <el-form-item label="用户名">
        <el-input v-model:="user.username" placeholder="请输入用户名"></el-input>
      </el-form-item>

      <el-form-item label="密码" >
        <el-input v-model:="user.password"show-password  placeholder="请输入密码"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" style="width: 100%;" @click="login()">登录</el-button>
      </el-form-item>

    </el-form>
  </el-card>
</template>

<script setup>
import {ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";
import qs from "qs";

const user = ref({username:'',password:''})
const login = () => {
  console.log(user.value)
  let data = qs.stringify(user.value);
  axios.post('http://localhost:8080/v1/users/login',data)
      .then((response)=>{
          if (response.data.code == 2001){
            let user = response.data.data;
            console.log(response.data.data)
            ElMessage.success("登录成功！欢迎 " + user.nickname + " 回来!!!");
            // user 是JS对象 不是字符串 所以需要先转换成字符串在存入JSON.stringfy(user)
            localStorage.setItem("user",JSON.stringify(user));
            router.push("/post")
          }else{
            //反之显示服务器响应的错误消息文本
            ElMessage.error(response.data.msg);
          }
      });
}

</script>



<style scoped>
  el-card{
    margin: 0 auto;
  }
</style>